import {
  wxRequest
} from '../../utils/server.js';
const _wxRequest = new wxRequest();
const app = getApp()
Page({
  data: {
    imgUrl: app.globalData.imgUrl, 
    uploadUrl: wx.getStorageSync('uploadUrl'),
  },
  

  //账号登陆
  accountLogin: function(e) { 
    var formdata = e.detail.value 
    _wxRequest.wxAjax({
      url: app.globalData.apiUrl +'/sys/jwt/mall/login',
      method: 'POST',
      data: formdata
    }, (res) => { 
      wx.hideLoading()     
      wx.setStorageSync('Authorization', res.Authorization);
      this.commonjum() 
      this.getUserInfo()
     

    })
  },


  //获取用户信息
  getUserInfo:function(){
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/odr/protected/customer/getLoginCustomer',
      method: 'get',
    }, (res) => {
      wx.hideLoading()
      //非微信头像拼接头部
      if (res.vo && res.vo.avatar) {
        var avatar = res.vo.avatar
        if (avatar.indexOf('https') == -1) { 
          res.vo.avatar = this.data.uploadUrl + avatar
        }
      }
      wx.setStorageSync('userInfo', res.vo); 
    })
  },


  //微信登陆
  wxlogin: function () {
    var that = this;
    wx.login({
      success: resLogin => {
        //获取用户信息
        wx.getSetting({
          success: res => {
            wx.getUserInfo({
              success: getUserres => {
                //用户信息 
                _wxRequest.wxAjax({
                  url: app.globalData.apiUrl + '/sys/jwt/mall/weixinLogin',
                  method: 'POST',
                  contentType: 'application/x-www-form-urlencoded',
                  data: {
                    code: resLogin.code, 
                    encryptedData: getUserres.encryptedData,
                    iv: getUserres.iv,
                    inviteStoId: wx.getStorageSync('inviteStoId'),
                    sharedCusId: wx.getStorageSync('sharedCusId'),
                    empUserId: wx.getStorageSync('empUserId')
                  },
                }, function (re) { 
                  wx.setStorageSync('Authorization', re);
                  that.commonjum()
                  that.getUserInfo()
                  
                })
              }
            })
          }
        })
      },
      fail(err) {
        wx.showToast({
          title: JSON.stringify(err),
          icon: 'none',
        })
      }
    })
  },

//跳转
commonjum:function(){
  var prePage = wx.getStorageSync('prePage')
  if (prePage) {
    wx.removeStorageSync('prePage') 
    //底部导航用switchTab，其他用跳转
    var wlist = ['/pages/index/index', '/pages/activity/index', '/pages/cart/index', '/pages/menber/index']
    if (wlist.indexOf(prePage) > -1) {
      wx.switchTab({
        url: prePage,
      })
    } else {
      wx.redirectTo({
        url: prePage,
      })
    } 
  } else {
    wx.switchTab({
      url: '/pages/index/index',
    })
  }
}

})